import Vue from 'vue'
import Vuex from 'vuex'
import router from "@/router"

Vue.use(Vuex)

const storePersist = (store) => {
  const key = 'SHAUN Q';
  const storage = window.sessionStorage;
  //取数
  const data = storage.getItem(key);
  data && store.replaceState(JSON.parse(data))
  //存储
  store.subscribe(function(mutation,state){
    console.log(mutation)
    storage.setItem(key, JSON.stringify(state))
  })
}

export default new Vuex.Store({
  state: {
    /**
     * 用户信息
     */
    user:{},
    /**
     * 菜单数据
     */
    menus:{},
  },
  getters: {
    token(state){
      return state.user.token;
    }
  },
  mutations: {
    /**
     * 设置用户信息
     */
    setUser(state,payload){
      state.user = payload
    },
    /**
     * 获取菜单数据
     */
    setMenus(state,payload){
      state.menus = payload
    }
  },
  actions: {
    /**
     * 退出
     */
    exit({commit}){
      commit("setUser",{})
      commit("setMenus",{})
      router.push({name:"Login"})
    }
  },
  modules: {
  },
  plugins:[storePersist]
})
